<template>
  <el-dialog v-model="addVisible" title="新增导线" width="500">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
      <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入名称" />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-input v-model="form.type" placeholder="请输入类型" />
      </el-form-item>
      <el-form-item label="初始长度" prop="long">
        <el-input v-model="form.long" placeholder="请输入初始长度" />
      </el-form-item>
      <el-form-item label="数量" prop="num">
        <el-input-number v-model="form.num" :min="1" :max="100" />
        <!-- <el-input v-model="form.num" placeholder="请输入数量" /> -->
      </el-form-item>
      <el-form-item>
        <div class="w-full flex justify-end">
          <el-button type="primary" @click="submitForm(formRef)"> 立即创建 </el-button>
          <el-button @click="$emit('closed')">取消</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import useWireState from '@/states/useWireStore'
import type { FormInstance, FormRules } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

interface ManyWireModel {
  name: string
  type: string
  long: number
  num: number
}

const formRef = ref<FormInstance>()
const addVisible = defineModel()
const route = useRoute()
const emit = defineEmits(['closed'])
const wireState = useWireState()
const form = reactive<ManyWireModel>({
  name: '',
  type: '',
  long: 2500,
  num: 1,
})

const formRules = reactive<FormRules<ManyWireModel>>({
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  type: [{ required: true, message: '请输入类型', trigger: 'blur' }],
  long: [{ required: true, message: '请输入初始长度', trigger: 'blur' }],
  num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
})

const submitForm = async (formRef: FormInstance | undefined) => {
  if (!formRef) return
  await formRef.validate(async (valid, fields) => {
    if (valid) {
      await wireState.add({ ...form, projId: route.params.id })
      await wireState.all({ projId: route.params.id })
      emit('closed')
    } else {
      console.log('error', fields)
    }
  })
}
</script>

<style></style>
